/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.entity.Brand;
import com.jeesite.modules.storage.service.ActivityService;
import com.jeesite.modules.storage.service.BrandService;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.service.AreaService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 品牌Controller
 */
@Controller(value = "webbrand")
@RequestMapping(value = "${adminPath}/storage/brand")
public class BrandController extends BaseController {

	@Autowired
	private BrandService brandService;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private AreaService areaService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Brand get(String id, boolean isNewRecord) {
		return brandService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequestMapping(value = {"list", ""})
	public String list(Brand brand, Model model) {
		model.addAttribute("brand", brand);
		Area area = new Area();
		area.setTreeLevel(0);
		List<Area> areas = areaService.findList(area);
		model.addAttribute("provinces", areas);
		return "modules/storage/brand/list";
	}

	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Brand> listData(Brand brand, HttpServletRequest request, HttpServletResponse response) {
		brand.setPage(new Page<>(request, response));
		return brandService.findPage(brand);
	}

	/**
	 * 查看编辑表单
	 */
	@RequestMapping(value = "form")
	public String form(Brand brand, Model model) {
		model.addAttribute("brand", brand);
		Area area = new Area();
		area.setTreeLevel(0);
		List<Area> areas = areaService.findList(area);
		model.addAttribute("provinces", areas);
		return "modules/storage/brand/form";
	}

	/**
	 * 保存品牌
	 */
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Brand brand) {
		try{
			brandService.save(brand);
			return renderResult(Global.TRUE, text("保存品牌成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}
	
	/**
	 * 删除品牌
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Brand brand) {
		try{
			brandService.delete(brand);
			return renderResult(Global.TRUE, text("删除品牌成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}

	/**
	 * 下载导入数据模板
	 */
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		importTemplate(response,"品牌 - 大仓库.xlsx");
	}

	/*
	 * 读取Excel到列表
	 */
	private List<Brand> readExcelToList(MultipartFile file){
		try {
			List<Brand> brands = new ArrayList<>();
			Workbook workbook = getWorkbook(file);
			Sheet sheet = workbook.getSheetAt(0);
			for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row row = sheet.getRow(rowNum);
				if (row == null  || row.getLastCellNum() < 6) {
					continue;
				}
				String sortStr = getCellValue(row,0);
				if(StringUtils.isBlank(sortStr)){
					continue;
				}
				Brand brand = new Brand();
				brand.setSort(Integer.parseInt(sortStr));
				brand.setLogo(getCellValue(row,1));
				brand.setLogo(getCellValue(row,2));
				brand.setLogo(getCellValue(row,3));
				brand.setName(getCellValue(row,4));
				brand.setContact(getCellValue(row,5));
				brand.setPhone(getCellValue(row,6));
				brand.setStore(getCellValue(row,7));
				brands.add(brand);
			}
			return brands;
		} catch (Exception ex) {
			throw ex;
		}
	}

	/*
	 * 读取Excel到列表
	 */
	private String check(List<Brand> brands){
		return "";
	}

	/**
	 * 导入数据
	 */
	@ResponseBody
	@PostMapping(value = "importData")
	public String importData(MultipartFile file) {
		try {
			List<Brand> brands = readExcelToList(file);
			String msg = check(brands);
			if(StringUtils.isNotBlank(msg)){
				return renderResult(Global.FALSE, "导入出错:" + msg);
			}
			for (Brand brand : brands){
				brand.setId(brandService.getIdByName(brand.getName()));
				if(StringUtils.isNotBlank(brand.getLogo())){
					brand.setLogo("/userfiles/brand/logo/"+brand.getLogo());
				}
				if(StringUtils.isNotBlank(brand.getTransparentLogo())){
					brand.setTransparentLogo("/userfiles/brand/transparentlogo/"+brand.getTransparentLogo());
				}
				if(StringUtils.isNotBlank(brand.getBackground())){
					brand.setBackground("/userfiles/brand/background/"+brand.getBackground());
				}
				brandService.save(brand);
			}
			return renderResult(Global.TRUE,"导入成功");
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
		}
	}
}